package com.esunny.online.controller.interceptor;

import com.esunny.online.domain.entity.User;
import com.esunny.online.service.UserService;
import com.esunny.online.util.CookieUtil;
import com.esunny.online.util.HostHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：李先生
 * @date ：Created in 2020/7/19 16:18
 * @description： 身份令牌拦截器
 * @modified By：
 * @version: $
 */
@Component
public class LoginTickInterceptor implements HandlerInterceptor {
    @Resource
    private HostHolder hostHolder;

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取令牌
        String ticket = CookieUtil.getValue(request, "ticket");

        //进行令牌判断
        if (ticket != null) {
            //这里 ticket就是用户名，可以根据具体进行处理
            User user = userService.selectByName(ticket);
            hostHolder.setUser(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null || modelAndView != null) {
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();//清除数据
    }
}
